package com.ruoyi.wxorali.service.impl;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.config.SystemConfig;
import com.ruoyi.wxorali.service.AliYunYuYinService;
import com.ruoyi.wxorali.service.QiNiuService;
import com.ruoyi.wxorali.utils.AliYunUtil;
import com.ruoyi.wxorali.utils.QiniuTokenGenerator;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import io.minio.errors.MinioException;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Service;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class QiNiuServiceImpl implements QiNiuService {
    @Resource
    private AliYunYuYinService aliYunYuYinService;

    public void qiNiuUploadImage(UploadManager uploadManager,String upToken, File folder, String prefix) {
        File[] files = folder.listFiles();
        if (files != null) {
            Map<String, Boolean> mapNotUp = new HashMap<>();
            // 先去检测文件到底符不符合上传的条件
            List<File> imagesList = new ArrayList<>();
            for (int i = 0; i < files.length; i++) {
                if (!files[i].isDirectory()) {
                    imagesList.add(files[i]);
                    if (i % 2 == 0) {
                        try {
                            JSONArray obj = aliYunYuYinService.generateImage(imagesList);
                            mapNotUp.putAll(AliYunUtil.resolvingJSON(obj));
                            imagesList = new ArrayList<>();
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        }
                    }
                }
            }
            if (imagesList.size() > 0) {
                try {
                    JSONArray obj = aliYunYuYinService.generateImage(imagesList);
                    mapNotUp.putAll( AliYunUtil.resolvingJSON(obj));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
            for (File file : files) {
                if (file.isDirectory()) {
                    // 如果是子文件夹，递归上传
                    String subFolderPrefix = prefix + file.getName() + "/";
                    qiNiuUploadImage(uploadManager, upToken, file, subFolderPrefix);
                } else {

                    if (!mapNotUp.containsKey(file.getName())){
                        //如果是Windows情况下，格式是 D:\\qiniu\\test.png
                        String localFilePath = file.getPath();
                        //默认不指定key的情况下，以文件内容的hash值作为文件名
                        String key =prefix + "/" + file.getName();
                        try {
                            Response response = uploadManager.put(localFilePath, key, upToken);
                            //解析上传成功的结果
                            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                            System.out.println(putRet.key);
                            System.out.println(putRet.hash);
                        } catch (QiniuException ex) {
                            ex.printStackTrace();
                            if (ex.response != null) {
                                System.err.println(ex.response);
                                try {
                                    String body = ex.response.toString();
                                    System.err.println(body);
                                } catch (Exception ignored) {
                                }
                            }
                        }
                    }
                }
            }

        }


    }

    @Override
    public void qiniuText(File nfile) {

        // 创建 Minio 客户端
        BufferedReader br = null;
        FileInputStream fis = null;
        InputStreamReader reader = null;
        try {
            fis = new FileInputStream(nfile);
            reader = new InputStreamReader(fis, "GBK");
            reader = new InputStreamReader(fis, "UTF-8");// 编码格式必须和文件的一致
            BufferedReader bufferedReader = new BufferedReader(reader);
            Region region = new Region.Builder()
                    .region("z0")
                    .accUpHost("up-cn-east-2.qiniup.com")
                    .srcUpHost("up-cn-east-2.qiniup.com")
                    .iovipHost("iovip.qiniuio.com")
                    .rsHost("rs.qiniu.com")
                    .rsfHost("rsf.qiniu.com")
                    .apiHost("api.qiniu.com")
                    .build();
            //构造一个带指定 Region 对象的配置类
            Configuration cfg = new Configuration(region);
            cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            String upToken = QiniuTokenGenerator.generateUploadToken("kewutu");
            String lineTxt = null;
            String resourceRoot = SystemConfig.getUploadMinio();
            while ((lineTxt = bufferedReader.readLine()) != null) {
                if (StringUtils.isNotEmpty(lineTxt)){
                    File folder = new File(resourceRoot+"/"+lineTxt);
                    qiNiuUploadImage(uploadManager, upToken, folder, lineTxt);
                }

            }


            System.out.println("图片上传成功！");
        } catch ( IOException e) {
            System.out.println("图片上传失败: " + e.getMessage());
        }
    }
}
